//! SQL解析器验证测试
//! 
//! 验证SQL解析器是否符合notepad中的严格实施要求：
//! 1. 诚实实现 - 真正的AST解析，非字符串匹配
//! 2. 测试驱动 - 全面的测试覆盖
//! 3. 功能完整 - 支持基础SQL语句

use cdb::sql::parser::{SqlParser, StatementType, WarningType};

#[test]
fn test_sql_parser_honest_implementation() {
    let parser = SqlParser::new();
    
    // 测试1: 验证真正的AST解析，而非字符串匹配
    let complex_sql = r#"
        SELECT u.id, u.name, COUNT(p.id) as post_count
        FROM users u
        LEFT JOIN posts p ON u.id = p.user_id
        WHERE u.created_at > '2023-01-01'
        GROUP BY u.id, u.name
        HAVING COUNT(p.id) > 5
        ORDER BY post_count DESC
        LIMIT 10
    "#;
    
    let result = parser.parse(complex_sql).unwrap();
    
    // 验证解析结果
    assert_eq!(result.statements.len(), 1);
    assert!(result.statistics.ast_node_count > 20); // 真正的AST应该有很多节点
    assert!(result.statistics.parse_time_us > 0); // 应该有解析时间
    
    // 验证是真正的SELECT语句解析
    if let sqlparser::ast::Statement::Query(_) = &result.statements[0] {
        // 正确解析为Query
    } else {
        panic!("应该解析为Query语句");
    }
}

#[test]
fn test_sql_parser_comprehensive_support() {
    let parser = SqlParser::new();
    
    // 测试SELECT语句
    let select_result = parser.parse("SELECT id, name FROM users WHERE age > 18").unwrap();
    assert_eq!(select_result.statements.len(), 1);
    assert_eq!(parser.get_sql_statement_type("SELECT id, name FROM users WHERE age > 18").unwrap(), StatementType::Select);
    
    // 测试INSERT语句
    let insert_result = parser.parse("INSERT INTO users (id, name, age) VALUES (1, 'Alice', 25)").unwrap();
    assert_eq!(insert_result.statements.len(), 1);
    assert_eq!(parser.get_sql_statement_type("INSERT INTO users (id, name, age) VALUES (1, 'Alice', 25)").unwrap(), StatementType::Insert);
    
    // 测试UPDATE语句
    let update_result = parser.parse("UPDATE users SET name = 'Bob' WHERE id = 1").unwrap();
    assert_eq!(update_result.statements.len(), 1);
    assert_eq!(parser.get_sql_statement_type("UPDATE users SET name = 'Bob' WHERE id = 1").unwrap(), StatementType::Update);
    
    // 测试DELETE语句
    let delete_result = parser.parse("DELETE FROM users WHERE id = 1").unwrap();
    assert_eq!(delete_result.statements.len(), 1);
    assert_eq!(parser.get_sql_statement_type("DELETE FROM users WHERE id = 1").unwrap(), StatementType::Delete);
    
    // 测试CREATE TABLE语句
    let create_result = parser.parse(r#"
        CREATE TABLE users (
            id SERIAL PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            email VARCHAR(255) UNIQUE
        )
    "#).unwrap();
    assert_eq!(create_result.statements.len(), 1);
    assert_eq!(parser.get_sql_statement_type("CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(100))").unwrap(), StatementType::CreateTable);
}

#[test]
fn test_sql_parser_error_handling() {
    let parser = SqlParser::new();
    
    // 测试无效SQL
    let result = parser.parse("INVALID SQL STATEMENT");
    assert!(result.is_err());
    
    // 测试空SQL
    let result = parser.parse("");
    assert!(result.is_err());
    
    // 测试只有空格的SQL
    let result = parser.parse("   ");
    assert!(result.is_err());
}

#[test]
fn test_sql_parser_warning_detection() {
    let parser = SqlParser::new();
    
    // 测试SELECT *警告
    let result = parser.parse("SELECT * FROM users").unwrap();
    assert!(!result.warnings.is_empty());
    assert!(result.warnings.iter().any(|w| w.warning_type == WarningType::Performance));
    
    // 测试缺少WHERE子句的UPDATE警告
    let result = parser.parse("UPDATE users SET name = 'test'").unwrap();
    assert!(!result.warnings.is_empty());
    
    // 测试缺少WHERE子句的DELETE警告
    let result = parser.parse("DELETE FROM users").unwrap();
    assert!(!result.warnings.is_empty());
}

#[test]
fn test_sql_parser_table_extraction() {
    let parser = SqlParser::new();
    
    // 测试单表提取
    let tables = parser.extract_table_names("SELECT * FROM users").unwrap();
    assert!(tables.contains(&"users".to_string()));
    
    // 测试多表JOIN提取
    let tables = parser.extract_table_names(
        "SELECT u.name, p.title FROM users u JOIN posts p ON u.id = p.user_id"
    ).unwrap();
    assert!(tables.len() >= 1);
    assert!(tables.contains(&"users".to_string()));
}

#[test]
fn test_sql_parser_analysis() {
    let parser = SqlParser::new();
    
    // 测试复杂查询分析
    let sql = r#"
        SELECT u.name, COUNT(p.id) as post_count
        FROM users u
        JOIN posts p ON u.id = p.user_id
        GROUP BY u.name
        HAVING COUNT(p.id) > 5
        ORDER BY post_count DESC
    "#;
    
    let analysis = parser.analyze(sql).unwrap();
    assert_eq!(analysis.statement_count, 1);
    assert!(analysis.has_joins);
    assert!(analysis.has_aggregates);
    assert!(analysis.complexity_score > 0);
}

#[test]
fn test_sql_parser_multiple_statements() {
    let parser = SqlParser::new();
    
    // 测试多条语句解析
    let sql = r#"
        SELECT * FROM users;
        INSERT INTO users (name) VALUES ('Alice');
        UPDATE users SET name = 'Bob' WHERE id = 1;
    "#;
    
    let result = parser.parse(sql).unwrap();
    assert_eq!(result.statements.len(), 3);
}

#[test]
fn test_sql_parser_dialect_support() {
    let parser = SqlParser::new();
    
    // 测试PostgreSQL特定语法
    let pg_sql = "SELECT * FROM users LIMIT 10 OFFSET 5";
    let result = parser.parse(pg_sql);
    assert!(result.is_ok());
    
    // 测试通用SQL语法
    let generic_sql = "SELECT COUNT(*) FROM users";
    let result = parser.parse(generic_sql);
    assert!(result.is_ok());
}

#[test]
fn test_sql_parser_performance() {
    let parser = SqlParser::new();
    
    // 测试解析性能
    let sql = "SELECT id, name, email FROM users WHERE age > 18 ORDER BY name";
    
    let start = std::time::Instant::now();
    let result = parser.parse(sql).unwrap();
    let duration = start.elapsed();
    
    // 解析应该很快（小于1ms对于简单查询）
    assert!(duration.as_millis() < 10);
    assert!(result.statistics.parse_time_us > 0);
}

#[test]
fn test_sql_parser_ast_node_counting() {
    let parser = SqlParser::new();
    
    // 简单查询应该有较少的AST节点
    let simple_result = parser.parse("SELECT id FROM users").unwrap();
    let simple_nodes = simple_result.statistics.ast_node_count;
    
    // 复杂查询应该有更多的AST节点
    let complex_result = parser.parse(r#"
        SELECT u.id, u.name, COUNT(p.id)
        FROM users u
        LEFT JOIN posts p ON u.id = p.user_id
        WHERE u.created_at > '2023-01-01'
        GROUP BY u.id, u.name
        ORDER BY COUNT(p.id) DESC
    "#).unwrap();
    let complex_nodes = complex_result.statistics.ast_node_count;
    
    // 复杂查询的节点数应该明显多于简单查询
    assert!(complex_nodes > simple_nodes * 2);
}

#[test]
fn test_sql_parser_statement_type_properties() {
    // 测试语句类型属性
    assert!(StatementType::Select.is_query());
    assert!(!StatementType::Select.is_modification());
    assert!(!StatementType::Select.is_ddl());
    
    assert!(!StatementType::Insert.is_query());
    assert!(StatementType::Insert.is_modification());
    assert!(!StatementType::Insert.is_ddl());
    
    assert!(!StatementType::CreateTable.is_query());
    assert!(!StatementType::CreateTable.is_modification());
    assert!(StatementType::CreateTable.is_ddl());
}
